package com.dragon.modules.yuegou.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@SuppressWarnings("rawtypes")
public class Tools {
	public static List deepCopy(List src) {
		List dest = null;
		try {
			ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(byteOut);
			out.writeObject(src);
			ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut
					.toByteArray());
			ObjectInputStream in = new ObjectInputStream(byteIn);
			dest = (List) in.readObject();

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e2) {
			e2.printStackTrace();
		}
		return dest;

	}

	// 左填充
	public static String lpad(String src, int length, char padValue) {
		if (src == null)
			src = "";
		int newLength = length;
		// 包含汉字并且不是window系统
		if (!System.getProperties().getProperty("os.name").startsWith("win")
				&& !System.getProperties().getProperty("os.name").startsWith(
						"Win") && getGBKLength(src) > 0) {
			try {
				newLength = length
						- (src.getBytes("GBK").length - src.length());
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {// 包含汉字时

			newLength = length;
		}
		int intLength = 0;
		try {
			intLength = newLength - src.getBytes("GBK").length;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String strTemp = "";
		for (int i = 0; i < intLength; i++) {
			strTemp += padValue;
		}
		return strTemp + src;

	}

	public static int getGBKLength(String src) {
		String len = "";
		int j = 0;

		char[] c = src.toCharArray();
		for (int i = 0; i < c.length; i++) {
			len = Integer.toBinaryString(c[i]);
			if (len.length() > 8)
				j++;
		}
		return j;
	}

	public static String rpad(String src, int length, char padValue) {
		if (src == null)
			src = "";
		int newLength = length;
		// 包含汉字并且不是window系统
		if (!System.getProperties().getProperty("os.name").startsWith("win")
				&& !System.getProperties().getProperty("os.name").startsWith(
						"Win") && getGBKLength(src) > 0) {
			/*
			 * try { newLength =
			 * length-(src.getBytes("GBK").length-src.length()); } catch
			 * (UnsupportedEncodingException e) { // TODO Auto-generated catch
			 * block e.printStackTrace(); }
			 */
			newLength = length;
		} else {// 包含汉字时

			newLength = length;
		}
		int intLength = 0;
		try {
			intLength = newLength - src.getBytes("GBK").length;
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String strTemp = "";
		for (int i = 0; i < intLength; i++) {
			strTemp += padValue;
		}
		return src + strTemp;
	}

	// 空值判断
	public static boolean checkNull(String src) {
		if (src == null || "".equals(src)) {
			return true;
		}

		return false;

	}
	

	private static final Random RANDOM = new Random();
	
	/*
	 * 取序列ID ID为前缀+随机数
	 */
	public static String getNextSpecId(String Prefix) {
		StringBuffer idStrBuff = new StringBuffer();
		if (Prefix != null && !"".equals(Prefix))
			idStrBuff.append(Prefix);
		for (int i = 0; i < 4; i++) {
			idStrBuff.append(RANDOM.nextInt(10));
		}
		System.out.println("NEW ID:" + idStrBuff.toString());
		return idStrBuff.toString();
	}

	/* *
	 * 获取随即数
	 */
	public static String getRandomByLength(int length) {
		StringBuffer strBuff = new StringBuffer();
		for (int i = 0; i < length; i++) {
			strBuff.append(RANDOM.nextInt(10));
		}
		return strBuff.toString();
	}
	
	public static String getCharAndNum(int length)     
	{     
	    String val = "";     
	             
	    Random random = new Random();   
	    String str = "1234567890"+
	    				"ABCDEFGHJKLMNPQRSTUVWXYZ";
	    for(int i = 0; i < length; i++)     
	    {     
	    	int ranNum = random.nextInt(34);
	    	val += str.substring(ranNum, ranNum+1);
	    }
	             
	    return val;     
	}
	
	/**
	 * 创建指定数量的随机字符串
	 * 
	 * @param numberFlag
	 *            是否是数字
	 * @param length
	 * @return
	 */
	public static String createRandom(boolean numberFlag, int length) {
		String retStr = "";
		String strTable = numberFlag ? "1234567890"
				: "1234567890abcdefghijkmnpqrstuvwxyz";
		int len = strTable.length();
		boolean bDone = true;
		do {
			retStr = "";
			int count = 0;
			for (int i = 0; i < length; i++) {
				double dblR = Math.random() * len;
				int intR = (int) Math.floor(dblR);
				char c = strTable.charAt(intR);
				if (('0' <= c) && (c <= '9')) {
					count++;
				}
				retStr += strTable.charAt(intR);
			}
			if (count >= 2) {
				bDone = false;
			}
		} while (bDone);

		return retStr;
	}
	
	/*
	 * 取序列ID ID为前缀+日期（14位）+随机数
	 */
	public static String getUUID() {
		return UUID.randomUUID().toString();
	}
	
	public static String get32UUID() {
		return getUUID().replaceAll("-", "");
	}
	
	public static String getOrderNo() {
		return getUUID().replaceAll("-", "");
	}
	
/*
	// 添加错误信息
	public static void setErrorMsg(String errorMsgCode, List<String> msgList) {
		Map session = (Map) ActionContext.getContext().get("session");
		List<String> errorList = (List<String>) session.get("ERRORMSG");
		if (errorList == null) {
			errorList = new ArrayList<String>();
		}
		if (msgList != null) {
			errorList.add(ParaManager.getInstance().getPara(errorMsgCode,
					msgList));
		} else {
			errorList.add(ParaManager.getInstance().getPara(errorMsgCode));
		}

		session.put("ERRORMSG", errorList);
		session.put("ERRORMSGJSON", Tools.toJson(errorList));
	}*/


	// 将字符串按照配置长度分割
	public static String[] praseCfgLengthStr(String str, int[] fieldLengths) {
		String[] fields = new String[fieldLengths.length];
		int splitLength = 0;
		for (int i = 0; i < fields.length; i++) {
			fields[i] = str.substring(splitLength, fieldLengths[i]);
			splitLength += fieldLengths[i];
		}
		return fields;
	}


	public static void zipFile(ZipOutputStream zos, File file, String fileName) {
		try (FileInputStream fis = new FileInputStream(file) ){
			zos.putNextEntry(new ZipEntry(fileName));
			int len;
			while ((len = fis.read()) != -1) {
				zos.write(len);
			}
		} catch (IOException e) {
			throw new UncheckedIOException(e);
		}
	}

	public static String formatMoney(String s) {
		if (s == null || s.length() < 1) {
			return "";
		}
		NumberFormat formater = null;
		double num = Double.parseDouble(s);
		formater = new DecimalFormat("#,###.00");
		return formater.format(num);

	}

	public static String formatCardNo(String cardNo) {
		String[] cardNos = cardNo.split(",");
		String card = null;
		StringBuffer cardNoBuf = new StringBuffer();
		for (int i = 0; i < cardNos.length; i++) {
			char[] cardArray = cardNos[i].toCharArray();
			if (cardNos[i].length() < 12) {
				cardNoBuf.append(cardNos[i]).toString();
			} else {
				for (int j = 6; j < 12; j++) {
					cardArray[j] = '*';
				}
				for (int a = 0; a < cardArray.length; a++) {
					cardNoBuf.append(cardArray[a]);
				}
			}
			cardNoBuf.append(",");
			card = cardNoBuf.toString();
		}

		return card.substring(0, card.length() - 1);
	}
	
	public static String[][] totalData(String[][] data) {
		data[data.length-1][0] = "总计";
		data[0][data[0].length-1] = "总计";
		for(int i=1;i<data[0].length-1;i++){
			Double curFieldTotal = 0.00;
			for(int j=1;j<data.length-1;j++){
				curFieldTotal+=new Double(data[j][i]);
			}
			data[data.length-1][i] = curFieldTotal+"";
		}
		for(int i=1;i<data.length;i++){
			Double curFieldTotal = 0.00;
			for(int j=1;j<data[0].length-1;j++){
				curFieldTotal+=new Double(data[i][j]);
			}
			data[i][data[0].length-1] = curFieldTotal+"";
		}
		return data;
	}
	
	public static double[][] getJFreeChartData(String[][] data) {
		double[][] doubleData = new double[data.length-2][data[0].length-2];
		for(int i=0;i<data.length-2;i++){
			for(int j=0;j<data[0].length-2;j++){
				doubleData[i][j]=new Double(data[i+1][j+1]);
			}
		}
		return doubleData;
	}
	
	public static double[][] getJFreeChartTotalData(String[][] data) {
		double[][] doubleData = new double[data.length-1][data[0].length-1];
		for(int i=0;i<data.length-1;i++){
			for(int j=0;j<data[0].length-1;j++){
				doubleData[i][j]=new Double(data[i+1][j+1]);
			}
		}
		return doubleData;
	}
	
	public static String[] getJFreeChartRow(String[][] data) {
		String[] rowData = new String[data[0].length-2];
		for(int i=0;i<data[0].length-2;i++){
			rowData[i] = data[0][i+1];
		}
		return rowData;
	}
	
	public static String[] getJFreeChartCol(String[][] data) {
		String[] colData = new String[data.length-2];
		for(int i=0;i<data.length-2;i++){
			colData[i] = data[i+1][0];
		}
		return colData;
	}
	
	public static String executeShell(String shellCommand) throws IOException {

		StringBuffer stringBuffer = new StringBuffer();

		BufferedReader bufferedReader = null;

		// 格式化日期时间，记录日志时使用

		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");

		try {

			stringBuffer.append(dateFormat.format(new Date())).append(
					"准备执行Shell命令 ").append(shellCommand).append(" \r\n");

			Process pid = null;

//			String[] cmd = { "/bin/bash", "-c", shellCommand };

			// 执行Shell命令

			pid = Runtime.getRuntime().exec(shellCommand);

			if (pid != null) {

				stringBuffer.append("进程号：").append(pid.toString()).append(
						"\r\n");

				// bufferedReader用于读取Shell的输出内容
				bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()),1024);

				pid.waitFor();

			} else {

				stringBuffer.append("没有pid\r\n");

			}

			stringBuffer.append(dateFormat.format(new Date())).append(
					"Shell命令执行完毕\r\n执行结果为：\r\n");

			String line = null;

			// 读取Shell的输出内容，并添加到stringBuffer中

			while (bufferedReader != null
					&& (line = bufferedReader.readLine()) != null) {

				stringBuffer.append(line).append("\r\n");
				

			}

		} catch (Exception ioe) {

			stringBuffer.append("执行Shell命令时发生异常：\r\n").append(ioe.getMessage())
					.append("\r\n");
			ioe.printStackTrace();

		}
		System.out.println(stringBuffer.toString());
		return stringBuffer.toString();

	}

	public static String transPara(Map<String,String> args, String content){
		String rsStr = content;
		if(args!=null){
			for(String key : args.keySet()){
				rsStr = rsStr.replaceAll("【"+key+"】", args.get(key));
			}
		}
		return rsStr;
	}


	private static double EARTH_RADIUS = 6378137;// 单位米

	/**
	 * 依据经纬度计算两点之间的距离 GetDistance:(). <br/>
	 *  单位 分米
	 *
	 * @author 程泽
	 * @param lat1
	 *            1点的纬度
	 * @param lng1
	 *            1点的经度
	 * @param lat2
	 *            2点的纬度
	 * @param lng2
	 *            2点的经度
	 * @return 距离 单位 米
	 * @since JDK 1.6
	 */
	public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
		double radLat1 = getRadian(lat1);
		double radLat2 = getRadian(lat2);
		double a = radLat1 - radLat2;// 两点纬度差
		double b = getRadian(lng1) - getRadian(lng2);// 两点的经度差
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1)
				* Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		return s;
	}


	/**
	 * 角度弧度计算公式 rad:(). <br/>
	 *
	 * 360度=2π π=Math.PI
	 *
	 * x度 = x*π/360 弧度
	 *
	 * @author cz
	 * @param degree
	 * @return
	 * @since JDK 1.8
	 */
	private static double getRadian(double degree) {
		return degree * Math.PI / 180.0;
	}
}
